package com.detech.sbom.business.user.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.detech.sbom.base.annotation.Log;
import com.detech.sbom.base.constant.CacheConstants;
import com.detech.sbom.base.domain.R;
import com.detech.sbom.base.domain.RE;
import com.detech.sbom.base.enumtype.LogTypeEnum;
import com.detech.sbom.base.enumtype.ModuleEnum;
import com.detech.sbom.base.redis.RedisUtils;
import com.detech.sbom.base.satoken.model.UserOnline;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 在线用户监控
 *
 */
@Api(tags = "在线用户监控管理")
@RestController
@RequestMapping("/online")
public class UserOnlineController {

    @Value(value = "${sa-token.token-name}")
    private String tokenName;

    @ApiOperation("未过期的用户会话列表")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "ipaddr", value = "IP地址", paramType = "query", dataTypeClass = String.class),
        @ApiImplicitParam(name = "username", value = "用户名", paramType = "query", dataTypeClass = String.class)
    })
    @Log(model = ModuleEnum.USER_MANAGE,logType = LogTypeEnum.INFO,value = "未过期的用户会话列表", saveDB = false)
    @GetMapping("/list")
    public RE<List<UserOnline>> list(String ipaddr, String username) {
        // 获取所有未过期的 token
        List<String> keys = StpUtil.searchTokenValue("", -1, -1,true);
        List<UserOnline> userOnlineList = new ArrayList<UserOnline>();
        for (String key : keys) {
            String token = key.replace(tokenName+CacheConstants.LOGIN_TOKEN_KEY, "");
            // 如果已经过期则跳过
            if (StpUtil.stpLogic.getTokenActivityTimeoutByToken(token) < 0) {
                continue;
            }
            UserOnline userOnline = RedisUtils.getCacheObject(CacheConstants.ONLINE_TOKEN_KEY + token);
            if(userOnline!=null)userOnlineList.add(userOnline);
        }
        if (StrUtil.isNotEmpty(ipaddr) && StrUtil.isNotEmpty(username)) {
            userOnlineList = userOnlineList.stream().filter(userOnline ->
                StrUtil.equals(ipaddr, userOnline.getIpaddr()) &&
                    StrUtil.equals(username, userOnline.getUserName())
            ).collect(Collectors.toList());
        } else if (StrUtil.isNotEmpty(ipaddr)) {
            userOnlineList = userOnlineList.stream().filter(userOnline ->
                    StrUtil.equals(ipaddr, userOnline.getIpaddr()))
                .collect(Collectors.toList());
        } else if (StrUtil.isNotEmpty(username)) {
            userOnlineList = userOnlineList.stream().filter(userOnline ->
                StrUtil.equals(username, userOnline.getUserName())
            ).collect(Collectors.toList());
        }
        Collections.reverse(userOnlineList);
        userOnlineList.removeAll(Collections.singleton(null));
        return R.ok(userOnlineList);
    }

    @ApiOperation("在线用户数量列表")
    @Log(model = ModuleEnum.USER_MANAGE,logType = LogTypeEnum.INFO,value = "在线用户数量列表", saveDB = false)
    @GetMapping("/userlist")
    public RE<List<UserOnline>> userlist() {
        // 获取所有未过期的 token
        List<String> keys = StpUtil.searchTokenValue("", -1, -1,true);
        List<UserOnline> userOnlineList = new ArrayList<UserOnline>();
        for (String key : keys) {
            String token = key.replace(tokenName+ CacheConstants.LOGIN_TOKEN_KEY, "");
            // 如果已经过期则跳过
            if (StpUtil.stpLogic.getTokenActivityTimeoutByToken(token) < 0) {
                continue;
            }
            UserOnline userOnline = RedisUtils.getCacheObject(CacheConstants.ONLINE_TOKEN_KEY + token);
            if(userOnline!=null)userOnlineList.add(userOnline);
        }
        if(userOnlineList.size()>1){
            //实体列表排序
            Collections.sort(userOnlineList, new Comparator<UserOnline>() {
                @Override
                public int compare(UserOnline o1, UserOnline o2) {
                    return o2.getLoginTime().compareTo(o1.getLoginTime());
                }
            });
        }
        if(userOnlineList.size()>1) {
            //列表去重
            userOnlineList = userOnlineList.stream().collect(
                    Collectors.collectingAndThen(
                            Collectors.toCollection(
                                    () -> new TreeSet<>(Comparator.comparing(UserOnline::getUserId))
                            )
                            , ArrayList::new
                    )
            );
        }
        return R.ok(userOnlineList);
    }

    /**
     * 强退用户
     */
    @ApiOperation("强退用户")
    @SaCheckPermission("system:online:forceLogout")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "tokenId", value = "tokenId", paramType = "query", dataTypeClass = String.class)
    })
    @Log(model = ModuleEnum.USER_MANAGE,logType = LogTypeEnum.WARN,value = "强退用户", saveDB = true)
    @PostMapping("/forceLogout")
    public RE forceLogout(String tokenId) {
        try {
            StpUtil.kickoutByTokenValue(tokenId);
        } catch (NotLoginException e) {
        }
        return R.ok();
    }
}
